package com.guilin.system.service.impl;

import com.guilin.common.core.domain.model.LoginUser;
import com.guilin.common.exception.ServiceException;
import com.guilin.common.utils.SecurityUtils;
import com.guilin.domain.ForumLikeRecord;
import com.guilin.mapper.ForumLikeRecordMapper;
import com.guilin.system.service.ForumLikeService;
import com.guilin.system.service.ForumThreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ForumLikeServiceImpl implements ForumLikeService {

    @Autowired
    private ForumLikeRecordMapper likeRecordMapper;

    @Autowired
    private ForumThreadService forumThreadService;


    /**
     * 点赞主题
     * @param threadId
     * @return
     */
    @Transactional
    public boolean likeThread(Long threadId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("用户未登录");
        }

        Long userId = loginUser.getUserId();

        // 检查是否已点赞
        if (hasLiked(threadId, userId)) {
            throw new ServiceException("您已经点过赞了");
        }

        // 创建点赞记录
        ForumLikeRecord record = new ForumLikeRecord();
        record.setThreadId(threadId);
        record.setUserId(userId);
        record.setUserType(loginUser.getUserType());

        int result = likeRecordMapper.insert(record);

        if (result > 0) {
            // 更新主题点赞数
            forumThreadService.updateLikeCount(threadId, 1);
            return true;
        }
        return false;
    }


    /**
     * 取消点赞主题
     * @param threadId
     * @return
     */
    @Transactional
    public boolean unlikeThread(Long threadId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("用户未登录");
        }

        Long userId = loginUser.getUserId();

        // 检查是否已点赞
        if (!hasLiked(threadId, userId)) {
            throw new ServiceException("您还没有点赞");
        }

        // 删除点赞记录
        int result = likeRecordMapper.deleteByThreadAndUser(threadId, userId);

        if (result > 0) {
            // 更新主题点赞数
            forumThreadService.updateLikeCount(threadId, -1);
            return true;
        }
        return false;
    }


    /**
     * 检查是否已点赞
     * @param threadId
     * @param userId
     * @return
     */
    public boolean hasLiked(Long threadId, Long userId) {
        return likeRecordMapper.countByThreadAndUser(threadId, userId) > 0;
    }
}
